<!-- 添加物料 -->
<template>
  <el-dialog custom-class="material-dialog" title="请选择BOM物料" :visible.sync="showDialog" width="70%" append-to-body="true" @close="closeBomDialog">
    <div class="titleBar" v-if="showSection"><i class="el-icon-vertical-bar"></i>用料工段</div>
    <avue-form class="infoForm" v-if="showSection" ref="selectSectionDialogForm" :option="sectionOption" v-model="selectSectionDialogForm"></avue-form>

    <div class="titleBar"><i class="el-icon-vertical-bar"></i>产品信息</div>
    <avue-form class="infoForm" ref="partInfoForm" :option="partInfo.option" v-model="partInfo.form"> </avue-form>

    <div class="titleBar"><i class="el-icon-vertical-bar"></i>BOM物料</div>
    <avue-form ref="materialForm" :option="material.option" v-model="material.form">
      <template slot="menuForm">
        <el-button type="primary" icon="el-icon-search" @click="handleSearchMaterial">搜索</el-button>
        <el-button icon="el-icon-delete" @click="handleClearMaterial">清空</el-button>
      </template>
    </avue-form>
    <avue-crud
      ref="materialCrud"
      :option="material.tableOption"
      :page.sync="material.page"
      :table-loading="material.tableLoading"
      :data="material.tableData"
      @selection-change="selectionMaterialChange"
      @row-click="handleRowClick"
      @current-change="currentMaterialChange"
      @size-change="sizeMaterialChange"
    >
    </avue-crud>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" icon="el-icon-circle-close" @click="materialCancel">取 消</el-button>
      <el-button type="primary" size="small" icon="el-icon-check" @click="materialSubmit">确 定</el-button>
    </span>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </el-dialog>
</template>

<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { mapGetters, mapState } from 'vuex';
import { getList as getBomVersionList, getBomList } from '@/api/admin/bom';
export default {
  components: {
    GlobalModalTemplate
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    productInfoList: {
      type: Array,
      default: () => []
    },
    showSection: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    visible: {
      handler(val) {
        this.showDialog = val;
      },
      immediate: true
    }
  },
  data() {
    return {
      visibile: false,
      bomList: [],
      showDialog: false,
      selectSectionDialogForm: {},
      sectionOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '用料工段',
            type: 'select',
            span: 8,
            prop: 'sectionId',
            dicData: []
          }
        ]
      },
      // 产品信息
      partInfo: {
        option: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '产品编码',
              prop: 'partNo',
              labelWidth: 85,
              type: 'search',
              span: 8,
              rules: [
                {
                  required: true,
                  message: '请输入产品编码',
                  trigger: 'blur'
                }
              ],
              appendClick: () => {
                this.openUserCommonModal({
                  type: 'partNo'
                });
              }
            },
            {
              label: '产品名称',
              prop: 'partName',
              labelWidth: 85,
              disabled: true,
              span: 8
            },
            {
              label: '产品型号',
              prop: 'partModel',
              labelWidth: 85,
              disabled: true,
              span: 8
            }
          ]
        },
        form: {}
      },
      // BOM物料
      material: {
        option: {
          submitBtn: false,
          emptyBtn: false,
          menuPosition: 'right',
          column: [
            {
              label: 'BOM版本',
              prop: 'bomId',
              labelWidth: 85,
              type: 'select',
              dicData: [],
              span: 8
            },
            {
              label: '物料编码',
              prop: 'partNo',
              labelWidth: 85,
              span: 8
            },
            {
              label: '物料名称',
              prop: 'name',
              labelWidth: 85,
              span: 8
            }
          ]
        },
        form: {},
        tableOption: {
          rowKey: 'bomDetailId',
          height: 300,
          border: true,
          index: true,
          indexLabel: '序号',
          tip: false,
          selection: true,
          addBtn: false,
          refreshBtn: false,
          columnBtn: false,
          menu: false,
          reserveSelection: true,
          selectable: (row, index) => {
            return !this.productInfoList.map((item) => item.partMasterId).includes(row.id);
          },
          column: [
            // {
            //   label: '产品编码',
            //   prop: 'cNo'
            // },
            // {
            //   label: '产品名称',
            //   prop: 'cName'
            // },
            {
              label: '产品型号',
              prop: 'partModel'
            },
            // {
            //   label: 'BOM版本',
            //   prop: 'bomId'
            // },
            {
              label: '物料编码',
              prop: 'partNo'
            },
            {
              label: '物料名称',
              prop: 'name'
            },
            {
              label: '物料类别',
              prop: 'categoryId',
              type: 'tree',
              dicUrl: '/api/mes-admin/part-category/tree',
              props: {
                label: 'title',
                value: 'id'
              }
            },
            {
              label: '物料规格',
              prop: 'partSpec'
            },
            {
              label: '用量',
              prop: 'unitQuantity'
            }
          ]
        },
        selectionList: [],
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        tableLoading: false,
        tableData: []
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.workorder_add, false),
        viewBtn: this.vaildData(this.permission.workorder_view, false),
        delBtn: this.vaildData(this.permission.workorder_delete, false),
        editBtn: this.vaildData(this.permission.workorder_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    basicInfoIndex() {
      let indexs = [];
      this.basicInfoSelectionList.forEach((ele) => {
        indexs.push(ele.$index);
      });
      return indexs;
    }
  },
  methods: {
    async initData(workSectionList, selectionList) {
      let data = structuredClone(workSectionList);
      let sectionId = this.findObject(this.sectionOption.column, 'sectionId');
      let bomIdIndex = this.material.option.column.findIndex((item) => item.prop == 'bomId');
      let bomId = null;
      sectionId.dicData = this._map(data, (item) => {
        return {
          label: item.sectionName,
          value: item.sectionId
        };
      });
      this.bomList = await this.getBomVersionData(selectionList[0].partNo);
      this.material.option.column[bomIdIndex].dicData = this.bomList;
      if (selectionList && selectionList.length > 0) {
        bomId = selectionList[0].bomId;
      }
      if (!bomId) {
        bomId = this._get(this.bomList, '[0].value', '');
      }
      this.material.form.bomId = bomId;
      // 设置产品信息默认值
      await this.setPartBaseInfo(selectionList[0]);
      // 获取BOM物料信息表格
      await this.baseGetBomData();
    },
    getBomVersionData(productPartNo) {
      return new Promise((resolve, reject) => {
        getBomVersionList(1, 10000, { productPartNo, sourceType: 'ERP', isAll: true })
          .then((res) => {
            let bomList = this._get(res, 'data.data.records', []);
            if (bomList.length > 0) {
              let data = this._map(bomList, (item) => {
                return {
                  label: item.bomVersion,
                  value: item.id
                };
              });
              resolve(data);
            } else {
              resolve([]);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 设置产品基础信息
    setPartBaseInfo(data) {
      this.$set(this.partInfo.form, 'partNo', data.partNo);
      this.$set(this.partInfo.form, 'partName', data.partName);
      this.$set(this.partInfo.form, 'partModel', data.partModel);
    },
    baseGetBomData() {
      this.material.page.currentPage = 1;
      this.material.page.pageSize = 15;
      this.getMaterialData();
    },
    // 获取物料列表数据
    getMaterialData() {
      this.material.tableLoading = true;
      getBomList(this.material.page.currentPage, this.material.page.pageSize, {
        ...this.material.form
      })
        .then((res) => {
          let data = res.data.data;
          this.$nextTick(() => {
            this.material.tableData = data.records;
            this.material.page.total = data.total;
          });
        })
        .catch((err) => {})
        .finally(() => {
          this.material.tableLoading = false;
        });
    },
    currentMaterialChange(currentPage) {
      this.material.page.currentPage = currentPage;
      this.getMaterialData();
    },
    sizeMaterialChange(pageSize) {
      this.material.page.pageSize = pageSize;
      this.getMaterialData();
    },
    selectionMaterialChange(list) {
      this.material.selectionList = list;
    },
    handleSearchMaterial() {
      this.baseGetBomData();
    },
    handleClearMaterial() {
      this.material.form.partNo = '';
      this.material.form.name = '';
      this.material.form.bomId = '';
      this.baseGetBomData();
    },
    handleRowClick(row) {
      let find = this.productInfoList.map((item) => item.partMasterId).includes(row.id);
      if (!find) {
        this.$refs.materialCrud.toggleRowSelection(row);
      }
    },
    materialSubmit() {
      console.log('this.material.selectionList', this.material.selectionList);
      let sectionId = this.findObject(this.sectionOption.column, 'sectionId');
      for (let i = 0; i < this.material.selectionList.length; i++) {
        let rowData = this.material.selectionList[i];
        if (this.showSection) {
          let workSectionObj = this._find(sectionId.dicData, { value: this.selectSectionDialogForm.sectionId });
          this.productInfoList.push({
            $index: this.productInfoList.length,
            partMasterId: rowData.id,
            partNo: rowData.partNo,
            partName: rowData.name,
            partModel: rowData.partModel ? rowData.partModel : '',
            partSpec: rowData.partSpec,
            quantity: rowData.unitQuantity,
            sectionId: this.selectSectionDialogForm.sectionId,
            sectionName: workSectionObj ? workSectionObj.label : ''
          });
        } else {
          this.productInfoList.push({
            $cellEdit: true,
            partMasterId: rowData.id,
            partNo: rowData.partNo,
            partName: rowData.name,
            partModel: rowData.partModel ? rowData.partModel : '',
            partSpec: rowData.partSpec,
            quantity: rowData.unitQuantity
          });
        }
      }

      this.showDialog = false;
      this.$emit('update:visible', false);
      this.material.selectionList = [];
      this.$refs.materialCrud.toggleSelection();
    },
    materialCancel() {
      this.closeBomDialog();
    },
    closeBomDialog() {
      if (this.showSection) {
        this.$refs.selectSectionDialogForm.resetFields();
        this.selectSectionDialogForm = {};
      }
      this.material.selectionList = [];
      this.$refs.materialCrud.toggleSelection();
      this.material.form.partNo = '';
      this.material.form.name = '';
      this.showDialog = false;
      this.$emit('update:visible', false);
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 产品编码
        case 'partNo':
          this.modalName = 'partNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90
          };
          this.tableOption.url = '/api/mes-admin/part-master/page';
          this.tableOption.isPage = true;
          this.tableOption.query = { semifinished: true };
          this.tableOption.templateName = 'NOWORKPARTMASTER';
          break;
        default:
          break;
      }
    },
    async getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partNoModal':
          let bomIdIndex = this.material.option.column.findIndex((item) => item.prop == 'bomId');
          this.$set(this.partInfo.form, 'partNo', rowData.partNo);
          this.$set(this.partInfo.form, 'partName', rowData.name);
          this.$set(this.partInfo.form, 'partModel', rowData.partModel);
          this.bomList = await this.getBomVersionData(rowData.partNo);
          this.material.option.column[bomIdIndex].dicData = this.bomList;
          this.material.form.bomId = this._get(this.bomList, '[0].value', '');
          await this.baseGetBomData();
          this.material.selectionList = [];
          this.$refs.materialCrud.toggleSelection();
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .material-dialog {
  margin-top: 5vh !important;
  .el-dialog__body {
    padding: 15px 20px;
    .titleBar {
      margin-bottom: 10px;
      font-weight: bold;
    }
    .infoForm {
      .avue-form__group {
        .el-col {
          &:last-child {
            display: none;
          }
        }
      }
    }
    .avue-crud__menu {
      display: none;
    }
  }
}
</style>
